package mspbots.cw.data.core.purchase;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.cw.common.ResultMsg;
import mspbots.cw.data.core.AbstractToolsUtil;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * com.mspbots.core.amqp.receivers.SchedulesReceiver
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/10/11
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class PurchaseOrdersReceiver extends AbstractToolsUtil {

    private final PurchaseOrdersRepository purchaseOrdersRepository;

    @RabbitListener(queues = "connect-wise.purchase-orders.sync")
    public void processMsg(ResultMsg resultMsg) {

        PurchaseOrders data = PurchaseOrders.builder()
                .otherId(resultMsg.getId())
                .tenantId(resultMsg.getTenantId())
                .extend(resultMsg.getEntity())
                .syncTime(resultMsg.getSyncDate())
                .build();

        if ("deleted".equalsIgnoreCase(resultMsg.getAction())) {
            this.purchaseOrdersRepository.deleteByTenantIdAndOtherId(data.getTenantId(), data.getOtherId())
                    .blockOptional(Duration.ofSeconds(10));
        } else {
            data.setUpdateTime(super.getUpdateTime(resultMsg.getEntity()));
            data.setCreateTime(super.getCreateTime(resultMsg.getEntity()));
            this.purchaseOrdersRepository.findByOtherIdAndTenantId(resultMsg.getId(), resultMsg.getTenantId())
                    .switchIfEmpty(this.purchaseOrdersRepository.save(data))
                    .filter(old -> old.getUpdateTime().isBefore(data.getUpdateTime()))
                    .map(result -> {
                        data.setId(result.getId());
                        return data;
                    })
                    .flatMap(this.purchaseOrdersRepository::save).block(Duration.ofSeconds(10));
        }

    }
}
